// 防止重复注入
if (!window.selectionButton) {
  window.selectionButton = true;

  // 创建翻译标签列表
  window.translationTags = [];

  // 记录当前加载的别名
  window.currentlyLoadedAlias = null;

  const btn = document.createElement('button');
  btn.id = 'selBtn';
  btn.textContent = '翻译';
  Object.assign(btn.style, {
    position: 'absolute',
    zIndex: 9999,
    display: 'none',
    padding: '4px 8px',
    border: '1px solid #ccc',
    background: '#fff',
    cursor: 'pointer'
  });
  document.body.appendChild(btn);

  let selectedRange = null; // 保存选中文本的范围
  let translation_index = 0;

  // 划词监听
  document.addEventListener('mouseup', (event) => {
    const sel = window.getSelection().toString().trim();
    if (sel) {
      selectedRange = window.getSelection().getRangeAt(0);
      // 使用鼠标位置而不是选中文本位置
      btn.style.left = `${event.clientX + window.scrollX}px`;
      btn.style.top  = `${event.clientY + window.scrollY + 5}px`;
      btn.style.display = 'block';
      btn.dataset.text = sel;
    } else {
      btn.style.display = 'none';
    }
  });

  // 点击按钮 → 发给后台
  btn.addEventListener('click', () => {
    const text = btn.dataset.text;
    if (!text) return;
    chrome.runtime.sendMessage({cmd: 'DO_TRANSLATE', text}, () => {
      btn.style.display = 'none';
      console.log('>>>已发送到后台');
    });
  });

  // 将 showTranslation 挂载到 window 对象，使其可以从外部访问
  window.showTranslation = showTranslation;

  // 监听来自 popup 的消息
  chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.cmd === 'SHOW_TRANSLATION') {
      showTranslation(request.translation);
      sendResponse({success: true});
    } else if (request.cmd === 'GET_TRANSLATION_TAGS') {
      // 返回当前页面的翻译标签列表
      sendResponse({tags: window.translationTags || []});
    } else if (request.cmd === 'LOAD_SAVED_TRANSLATION') {
      // 加载保存的翻译内容
      loadSavedTranslation(request.labels, request.alias);
      sendResponse({success: true});
    } else if (request.cmd === 'GET_CURRENT_ALIAS') {
      // 返回当前加载的别名
      sendResponse({alias: window.currentlyLoadedAlias});
    }  else if (request.cmd === 'SET_CURRENT_ALIAS') {
      // 设置当前加载的别名
      window.currentlyLoadedAlias = request.alias;
      sendResponse({success: true});
    }else if (request.cmd === 'CLEAR_TRANSLATION_BOXES') {
      // 清除所有翻译标签
      clearTranslationBoxes();
      sendResponse({success: true});
    }
  });

  // 添加清除所有翻译标签的函数
  function clearTranslationBoxes() {
    // 移除所有翻译标签元素
    const existingBoxes = document.querySelectorAll('[id^="translationBox_"]');
    existingBoxes.forEach(box => {
      document.body.removeChild(box);
    });
    
    // 清空翻译标签列表
    window.translationTags = [];
  }

  // 加载保存的翻译内容函数
  function loadSavedTranslation(labels, alias) {
    // 设置当前加载的别名
    window.currentlyLoadedAlias = alias;

    // 清除现有的所有翻译标签
    const existingBoxes = document.querySelectorAll('[id^="translationBox_"]');
    existingBoxes.forEach(box => {
      document.body.removeChild(box);
    });
    
    // 清空翻译标签列表
    window.translationTags = [];
    
    // 根据保存的数据重新创建翻译标签
    labels.forEach((label, index) => {
      createTranslationBox(label, index);
    });
  }

  // 显示翻译结果
  function showTranslation(translation) {
    // 创建翻译结果显示元素
    let translationBox = document.createElement('div');
    translationBox.id = 'translationBox_' + translation_index;
    Object.assign(translationBox.style, {
      position: 'absolute',
      zIndex: 9998,
      display: 'none',
      padding: '8px 12px',
      background: 'rgba(255, 255, 255, 0.7)',
      border: '1px solid #ddd',
      borderRadius: '4px',
      boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
      fontSize: '14px',
      color: 'red',
      fontWeight: 'bold',
      wordWrap: 'break-word',
      lineHeight: '1.4'
    });

    // 创建关闭按钮
    const closeBtn = document.createElement('span');
    closeBtn.innerHTML = '&times;';
    Object.assign(closeBtn.style, {
      position: 'absolute',
      top: '2px',
      right: '4px',
      fontSize: '16px',
      fontWeight: 'bold',
      cursor: 'pointer',
      color: '#999'
    });

    closeBtn.addEventListener('click', () => {
      // 关闭时从列表中删除记录
      const index = window.translationTags.findIndex(tag => tag.id === translationBox.id);
      if (index !== -1) {
        window.translationTags.splice(index, 1);
      }
      document.body.removeChild(translationBox);
    });

    translationBox.appendChild(closeBtn);
    document.body.appendChild(translationBox);

    // 设置翻译内容（注意避开关闭按钮）
    const contentDiv = document.createElement('div');
    Object.assign(contentDiv.style, {
      paddingRight: '20px' // 给关闭按钮留出空间
    });
    contentDiv.textContent = translation;
    translationBox.appendChild(contentDiv);
    
    let boxLeft, boxTop, boxWidth;
    if (selectedRange) {
      // 获取选中文本的边界矩形
      const rect = selectedRange.getBoundingClientRect();
      boxWidth = rect.width;
      // 定位到选中文本下方
      boxLeft = rect.left + window.scrollX;
      boxTop = rect.top + window.scrollY + 5;
      
      // 设置宽度与选中区域相同
      translationBox.style.width = `${boxWidth}px`;
      translationBox.style.left = `${boxLeft}px`;
      translationBox.style.top = `${boxTop}px`;
    }
    
    translationBox.style.display = 'block';

    // 创建标签记录并添加到列表
    const tagRecord = {
      id: translationBox.id,
      content: translation,
      left: boxLeft,
      top: boxTop,
      width: boxWidth
    };
    window.translationTags.push(tagRecord);

    // 添加拖动功能
    makeDraggable(translationBox);

    translation_index += 1;
  }

  // 创建单个翻译标签
  function createTranslationBox(label, index) {
    // 创建翻译结果显示元素
    let translationBox = document.createElement('div');
    translationBox.id = 'translationBox_' + index;
    Object.assign(translationBox.style, {
      position: 'absolute',
      zIndex: 9998,
      display: 'block',
      padding: '8px 12px',
      background: 'rgba(255, 255, 255, 0.7)',
      border: '1px solid #ddd',
      borderRadius: '4px',
      boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
      fontSize: '14px',
      color: 'red',
      fontWeight: 'bold',
      wordWrap: 'break-word',
      lineHeight: '1.4',
      width: `${label.width}px`,
      left: `${label.left}px`,
      top: `${label.top}px`
    });

    // 创建关闭按钮
    const closeBtn = document.createElement('span');
    closeBtn.innerHTML = '&times;';
    Object.assign(closeBtn.style, {
      position: 'absolute',
      top: '2px',
      right: '4px',
      fontSize: '16px',
      fontWeight: 'bold',
      cursor: 'pointer',
      color: '#999'
    });

    closeBtn.addEventListener('click', () => {
      // 关闭时从列表中删除记录
      const index = window.translationTags.findIndex(tag => tag.id === translationBox.id);
      if (index !== -1) {
        window.translationTags.splice(index, 1);
      }
      document.body.removeChild(translationBox);
    });

    translationBox.appendChild(closeBtn);
    document.body.appendChild(translationBox);

    // 设置翻译内容
    const contentDiv = document.createElement('div');
    Object.assign(contentDiv.style, {
      paddingRight: '20px'
    });
    contentDiv.textContent = label.contents;
    translationBox.appendChild(contentDiv);

    // 创建标签记录并添加到列表
    const tagRecord = {
      id: translationBox.id,
      content: label.contents,
      left: label.left,
      top: label.top,
      width: label.width
    };
    window.translationTags.push(tagRecord);

    // 添加拖动功能
    makeDraggable(translationBox);
  }

  // 在创建 translationBox 时添加拖动功能
  function makeDraggable(element) {
    let isDragging = false;
    let startX, startY, startLeft, startTop;

    // 鼠标按下事件
    element.addEventListener('mousedown', (e) => {
      // 忽略关闭按钮的点击
      if (e.target === element.querySelector('span')) return;
      
      isDragging = true;
      startX = e.clientX;
      startY = e.clientY;
      startLeft = element.offsetLeft;
      startTop = element.offsetTop;
      
      // 添加鼠标移动和释放事件到 document 上
      document.addEventListener('mousemove', handleMouseMove);
      document.addEventListener('mouseup', handleMouseUp);
      
      // 防止文本选择
      e.preventDefault();
    });

    // 处理鼠标移动
    function handleMouseMove(e) {
      if (!isDragging) return;
      
      const deltaX = e.clientX - startX;
      const deltaY = e.clientY - startY;
      
      const newLeft = startLeft + deltaX;
      const newTop = startTop + deltaY;
      
      element.style.left = `${newLeft}px`;
      element.style.top = `${newTop}px`;
      
      // 更新 translationTags 中的记录
      const tagIndex = window.translationTags.findIndex(tag => tag.id === element.id);
      if (tagIndex !== -1) {
        window.translationTags[tagIndex].left = newLeft;
        window.translationTags[tagIndex].top = newTop;
      }
    }

    // 处理鼠标释放
    function handleMouseUp() {
      isDragging = false;
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
    }
  }

  // 监听浏览器历史记录变化
  let lastUrl = location.href;
  new MutationObserver(() => {
      const url = location.href;
      if (url !== lastUrl) {
          lastUrl = url;
          // 清除之前添加的翻译标签
          clearTranslationBoxes();
      }
  }).observe(document, { subtree: true, childList: true });

  // 监听popstate事件（浏览器前进后退）
  window.addEventListener('popstate', function() {
      clearTranslationBoxes();
  });
}

